<template>
  <div class="app-container">
    <label class="title" style="font-size: 20px;color: rgba(0,0,0,.85);font-weight: 600;line-height: 32px">版本管理</label>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="版本号" prop="versionCode">
        <el-input
          v-model="queryParams.versionCode"
          placeholder="请输入版本号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否强制更新" prop="versionCompelUpdate">
        <el-select v-model="queryParams.versionCompelUpdate" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in dict.type.versionCompelUpdate"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:records:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{scope.$index+(queryParams.pageNum-1)*queryParams.pageSize+1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="versionCode" />
      <el-table-column label="版本号整型" align="center" prop="versionIntCode" />
      <el-table-column label="版本名称" align="center" prop="versionName" />
      <el-table-column label="版本描述" align="center" prop="versionDescrption" />
      <el-table-column label="是否强制更新" align="center" prop="versionCompelUpdate" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.versionCompelUpdate" :value="scope.row.versionCompelUpdate"/>
        </template>
      </el-table-column>
      <el-table-column label="版本更新时间" align="center" prop="gmtModified" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtModified, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="gmtCreated" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreated, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="download(scope.row)"
          >下载
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:records:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:records:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改版本更新记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="form.versionCode" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="版本号整型" prop="versionIntCode">
          <el-input v-model="form.versionIntCode" placeholder="请输入版本号整型" />
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="版本描述" prop="versionDescrption">
          <el-input v-model="form.versionDescrption" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="版本文件" prop="versionFileUrl">
          <el-input type="textarea" :rows="2" v-model="form.versionFileUrl" :disabled="true"/>
          <el-upload ref="upload" action="#" :http-request="requestUpload" :show-file-list="true" :limit="1" accept=".apk"
                     :before-upload="uploadFile">
            <el-button type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            <div slot="tip" class="el-upload__tip">仅支持.apk文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否强制更新" prop="versionCompelUpdate">
          <el-select v-model="form.versionCompelUpdate" placeholder="请选择" clearable size="small">
            <el-option
              v-for="dict in dict.type.versionCompelUpdate"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import { listRecords, getRecords, delRecords, addRecords, updateRecords, uploadApkFile } from "@/api/business/versionRecords/versionRecords";

    export default {
        name: "Records",
        dicts:["versionCompelUpdate"],
        data() {
            return {
                // 遮罩层
                loading: true,
                // 导出遮罩层
                exportLoading: false,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 版本更新记录表格数据
                recordsList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    versionCode: null,
                    versionName: null,
                    deviceType: null,
                    versionFileUrl: null,
                    versionCompelUpdate: null,
                    versionDescrption: null,
                    gmtModified: null,
                    gmtCreated: null,
                    versionIntCode: null
                },
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                    versionCode: [
                        { required: true, message: '版本号不能为空', trigger: 'blur' }
                    ],
                    versionName: [
                        { required: true, message: '版本名称不能为空', trigger: 'blur' }
                    ],
                    versionFileUrl: [
                        { required: true, message: '版本文件不能为空', trigger: 'blur' }
                    ],
                    versionCompelUpdate: [
                        { required: true, message: '请选择是否强制更新', trigger: 'blur' }
                    ],
                    versionDescrption: [
                        { required: true, message: '版本描述不能为空', trigger: 'blur' }
                    ],
                    versionIntCode: [
                        { required: true, message: '版本号整型不能为空', trigger: 'blur' }
                    ]
                },
                apkFile: null,
            };
        },
        created() {
            this.getList();
        },
        methods: {
            /** 查询版本更新记录列表 */
            getList() {
                this.loading = true;
                listRecords(this.queryParams).then(response => {
                    this.recordsList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    versionCode: null,
                    versionName: null,
                    deviceType: null,
                    versionFileUrl: null,
                    versionCompelUpdate: null,
                    versionDescrption: null,
                    gmtModified: null,
                    updateBy: null,
                    gmtCreated: null,
                    createBy: null,
                    versionIntCode: null
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length!==1
                this.multiple = !selection.length
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加版本更新记录";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id || this.ids
                getRecords(id).then(response => {
                    this.form = response.data;
                    this.form.versionCompelUpdate = response.data.versionCompelUpdate+'';
                    this.open = true;
                    this.title = "修改版本更新记录";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            updateRecords(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addRecords(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$modal.confirm('是否确认删除版本更新记录编号为"' + ids + '"的数据项？').then(function() {
                    return delRecords(ids);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => {});
            },
            // 覆盖默认的上传行为
            requestUpload() {
            },
            // 上传文件
            uploadFile(file) {
                var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
                const extension = testmsg === "apk";
                if (!extension) {
                    this.$message({
                        message: "上传文件只能是.apk格式!",
                        type: "warning",
                    });
                } else {
                    const reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.apkFile = file
                        let formData = new FormData()
                        formData.append('apkFile', this.apkFile)
                        uploadApkFile(formData).then(response => {
                            this.form.versionFileUrl = response.apkFileUrl
                            this.$modal.msgSuccess('上传成功')
                        })
                    }
                }
            },
            // 文件下载
            download(row) {
                var name = row.versionCode+" "+row.versionName;
                var url = row.versionFileUrl;
                const a = document.createElement('a')
                // a.setAttribute('download', name)
                a.setAttribute('target', '_self')
                a.setAttribute('href', process.env.VUE_APP_BASE_API  + url)
                a.click()
            },
        }
    };
</script>
